﻿using Microsoft.Extensions.DependencyInjection;
using PineLake.Drmwe.SystemConfig;
using SqlSugar.IOC;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace PineLake.Drmwe.Core.ORM
{
    /// <summary>
    /// SqlSugar服务
    /// </summary>
    public static class SqlSugarStartup
    {
        public static void AddSqlSugarStartup(this IServiceCollection Service)
        {
            if (Service == null) throw new ArgumentNullException(nameof(Service));

            var ListConfig = new List<IocConfig>();
            var SqlConnList = AppSettings.MultipleDbsConn;
            SqlConnList.ForEach(MultsConn =>
            {
                ListConfig.Add(new IocConfig()
                {
                    DbType = MultsConn.DbType== IocDbType.SqlServer.ToString() ? IocDbType.SqlServer : IocDbType.MySql,
                    ConnectionString = MultsConn.SqlConnection,
                    IsAutoCloseConnection = true,
                    ConfigId = MultsConn.ConfigId,
                });
            });
            Service.AddSqlSugar(ListConfig);

            //配置参数
            Service.ConfigurationSugar(db =>
            {
                SqlConnList.ForEach(q =>
                {
                    //执行前
                    db.GetConnectionScope(q.ConfigId).Aop.OnLogExecuting = (sql, p) =>
                    {
                        //Console.WriteLine(sql);//输出sql
                        Console.WriteLine(UtilMethods.GetNativeSql(sql, p));//输出sql
                        Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));//参数

                    };
                    ////执行时间大于一秒
                    //db.GetConnection(q.ConfigId).Aop.OnLogExecuted = (sql, p) =>
                    //{
                    //    Console.WriteLine(sql);//输出sql
                    //    Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));//参数
                    //    //Console.WriteLine(db.GetConnection(q.ConfigId).Ado.SqlExecutionTime.TotalSeconds);//输出sql
                    //    if (db.GetConnection(q.ConfigId).Ado.SqlExecutionTime.TotalSeconds > 0.01)
                    //    {
                    //        //代码CS文件名
                    //        var fileName = db.GetConnection(q.ConfigId).Ado.SqlStackTrace.FirstFileName;
                    //        //代码行数
                    //        var fileLine = db.GetConnection(q.ConfigId).Ado.SqlStackTrace.FirstLine;
                    //        //方法名
                    //        var FirstMethodName = db.GetConnection(q.ConfigId).Ado.SqlStackTrace.FirstMethodName;

                    //        //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息
                    //        var Fn = db.GetConnection(q.ConfigId).Ado.SqlStackTrace.MyStackTraceList[1].FileName;
                    //        Console.WriteLine($"fileName: {fileName} fileLine:{fileLine} FirstMethodName: {FirstMethodName} Fn:{Fn}");//输出sql
                    //    }
                    //    //Console.WriteLine(sql);//输出sql
                    //    //Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));//参数
                    //};
                    //执行SQL 错误事件
                    db.GetConnectionScope(q.ConfigId).Aop.OnError = (exp) =>
                    {
                        //NLogUtil.WriteFileLog(NLog.LogLevel.Error, LogType.Other, "SqlSugar", "执行SQL错误事件", exp);
                        Console.WriteLine("执行SQL错误!", exp);
                        //throw new Exception("执行SQL错误!", exp);
                    };

                    db.GetConnectionScope(q.ConfigId).Aop.OnLogExecuted = (sql, p) =>
                    {
                        //Console.WriteLine(UtilMethods.GetNativeSql(sql, p));
                        if (p.Length > 0)
                        {
                            foreach (var item in p)
                            {
                                sql = sql.Replace(item.ParameterName.ToString(), $"'{item.Value?.ToString()}'");
                            }
                        }
                        var ExecutionTime = db.GetConnectionScope(q.ConfigId).Ado.SqlExecutionTime.TotalSeconds.ToString(); ;//执行SQL语句时间
                        Console.WriteLine($"执行后SQL: {sql} 执行时间: {ExecutionTime} 秒");
                    };
                });
                //设置更多连接参数
                //db.CurrentConnectionConfig.XXXX=XXXX
                //db.CurrentConnectionConfig.MoreSettings=new ConnMoreSettings(){}
                //二级缓存设置
                //db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices()
                //{
                // DataInfoCacheService = myCache //配置我们创建的缓存类
                //}
                //读写分离设置
                //laveConnectionConfigs = new List<SlaveConnectionConfig>(){...}

                /*多租户注意*/
                //单库是db.CurrentConnectionConfig 
                //多租户需要db.GetConnection(configId).CurrentConnectionConfig 
            });
        }
    }
}
